Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 33/43 Β· 161.3 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
implicitly cast to false). Within the function, the arguments may also
be accessed through the arguments object; this provides access to all
arguments using indices (e.g. arguments[0], arguments[1], ...
arguments[n]), including those beyond the number of named arguments.
(While the arguments list has a .length property, it is not an instance
of Array; it does not have methods such as .slice(), .sort(), etc.)

function add7(x, y) {
if (!y) {
y = 7;
}
console.log(x + y + arguments.length);
};
add7(3); // 11
add7(3, 4); // 9

Primitive values (number, boolean, string) are passed by value. For
objects, it is the reference to the object that is passed.

const obj1 = {a : 1};
const obj2 = {b : 2};
function foo(p) {
p = obj2; // Ignores actual parameter
p.b = arguments[1];
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
console.log(`${obj1.a} ${obj2.b}`); // writes 1 3

Functions can be declared inside other functions, and access the outer
function's local variables. Furthermore, they implement full closures by
remembering the outer function's local variables even after the outer
function has exited.

let t = "Top";
let bar, baz;
function foo() {
let f = "foo var";
bar = function() { console.log(f) };
baz = function(x) { f = x; };
}
foo();
baz("baz arg");
bar(); // "baz arg" (not "foo var") even though foo() has exited.
console.log(t); // Top

An anonymous function is simply a function without a name and can be
written either using function or arrow notation. In these equivalent
examples an anonymous function is passed to the map function and is
applied to each of the elements of the array.cite-ref-20[20]

[1,2,3].map(function(x) { return x*2;); //returns [2,4,6]
[1,2,3].map((x) => { return x*2;}); //same result

A generator function is signified placing an * after the keyword
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────